/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SkinChooser.java
 *
 * Created on May 20, 2010, 12:09:07 AM
 */
package jeffoldwork;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.io.*;
import java.nio.channels.FileChannel;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.*;
import javax.swing.*;

/**
 * @author Alex Koutmos
 */
public class SkinChooser extends javax.swing.JFrame {

    private SkinSelectPanel active = null;

    /** Creates new form SkinChooser */
    public SkinChooser() {
        //Set look and feel
        try {
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
        }
        initComponents();
        //validate();
        //setSize(java.awt.Toolkit.getDefaultToolkit().getScreenSize());
        setResizable(true);
        validate();
        setVisible(true);

        availablePanelScroll.setLayout(new ScrollPaneLayout());
        availablePanel.setLayout(new FlowLayout());
       
        getCharacterList();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        updateButton = new javax.swing.JButton();
        characterDropdown = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        availablePanelScroll = new javax.swing.JScrollPane();
        availablePanel = new javax.swing.JPanel();
        currentSkinAuthor = new javax.swing.JLabel();
        currentSkinName = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("LoL Skin Chooser by Aurabolt and koutz4");
        setName(""); // NOI18N

        updateButton.setText("Update");
        updateButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                updateButtonMouseReleased(evt);
            }
        });
        updateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateButtonActionPerformed(evt);
            }
        });

        characterDropdown.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                characterDropdownActionPerformed(evt);
            }
        });

        jLabel1.setText("Currently Selected Skin for:");

        javax.swing.GroupLayout availablePanelLayout = new javax.swing.GroupLayout(availablePanel);
        availablePanel.setLayout(availablePanelLayout);
        availablePanelLayout.setHorizontalGroup(
            availablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 984, Short.MAX_VALUE)
        );
        availablePanelLayout.setVerticalGroup(
            availablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 594, Short.MAX_VALUE)
        );

        availablePanelScroll.setViewportView(availablePanel);

        currentSkinAuthor.setText("currentSkinAuthor");

        currentSkinName.setText("currentSkinName");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(characterDropdown, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(currentSkinName, javax.swing.GroupLayout.PREFERRED_SIZE, 363, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(currentSkinAuthor, javax.swing.GroupLayout.DEFAULT_SIZE, 316, Short.MAX_VALUE))
                    .addComponent(availablePanelScroll, javax.swing.GroupLayout.DEFAULT_SIZE, 986, Short.MAX_VALUE)
                    .addComponent(updateButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 986, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(characterDropdown, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(currentSkinName)
                    .addComponent(currentSkinAuthor))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(availablePanelScroll, javax.swing.GroupLayout.DEFAULT_SIZE, 596, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(updateButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void updateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateButtonActionPerformed

        try {
            //Declaration of variables

            String url = "http://auranet.no-ip.org/";
            String filename = "Characters.zip"; // parse here to get filename from url
            String destination = "C:\\Riot Games\\League of Legends\\game\\DATA\\";

            BufferedInputStream getFile = new BufferedInputStream(new URL(url + filename).openStream());
            BufferedOutputStream writeFile = new BufferedOutputStream(new FileOutputStream(destination + filename), 1024);

            int oneChar, count = 0;
            while ((oneChar = getFile.read()) != -1) {
                writeFile.write(oneChar);
                count++;
            }

            writeFile.close();
            getFile.close();
  
            Unzip.unzip(destination + filename);
        } catch (Exception e) {
            System.out.println("Fail");
        }

        getCharacterList();
    }//GEN-LAST:event_updateButtonActionPerformed

    public void getCharacterList() {
        // Get list of characters from Characters folder
        File dir = new File("C:\\Riot Games\\League of Legends\\game\\DATA\\Characters");
        String[] children = dir.list();
        if (children == null) {
            // Either dir does not exist or is not a directory
            System.out.println("Directory does not exist or is not a directory");
        } else {
            for (int i = 0; i < children.length; i++) { // Get filename of file or directory
                String filename = children[i];
            }
        }

        // Populate Dropdown with character names
        characterDropdown.removeAll();
        for (int i = 0; i < children.length; i++) {
            characterDropdown.addItem(children[i]);
        }
    }

    /**
     * Get the available skins for the character (folder names)
     * @param character The Champion's name (folder name)
     */
    public void getAvailableList(String character) {
        String root = "C:\\Riot Games\\League of Legends\\game\\DATA\\Characters\\";
        // Get list of characters from Characters folder
        File dir = new File(root + character);
        String[] children = dir.list();

        // Next 2 lines is shitty code
        String[] availableSkins = new String[100];
        SkinSelectPanel[] skins = new SkinSelectPanel[100];
        int count = 0;
        int counter = 0;

        if (children == null)
        {
            // Either dir does not exist or is not a directory
            System.out.println("Directory does not exist or is not a directory");
        } 
        else
        {
            for (int i = 0; i < children.length; i++)
            { // Get filename of file or directory
                if (new File(root + "\\" + character + "\\" + children[i]).isDirectory())
                {
                    availableSkins[count] = children[i];
                    count++;
                }
            }
        }

        // Populate Available skin chooser
        availablePanel.removeAll();
        for (int i = 0; i < count; i++)
        {
            counter = 0;
            // Get and display available skin picture
            String imageLocation = "C:\\Riot Games\\League of Legends\\game\\DATA\\Characters\\" + character + "\\" +availableSkins[i] +"\\" +character +".jpg";
            String authorLocation = "C:\\Riot Games\\League of Legends\\game\\DATA\\Characters\\" + character + "\\" + availableSkins[i] + "\\" + "author.txt";
            ImageIcon icon = new ImageIcon(imageLocation);

            icon = resizeImageIcon(icon);

            String strLine;
            String thisAuthor = "";
            try {
                BufferedReader in = new BufferedReader(new FileReader(authorLocation));
                while ((strLine = in.readLine()) != null) {
                    if (counter == 0) {
                        // Print the author to the JLabel
                        thisAuthor = "by: " + strLine;
                        counter++;
                    }
                }
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            // Add skin as SkinSelectPanel
            SkinSelectPanel addMe = new SkinSelectPanel(icon, availableSkins[i], thisAuthor);
            availablePanel.add(addMe);
        }

        // Highlight currently selected skin
        this.activator(getCurrentSkinName(character));
    }

    /**
     * Gets the current skin name from character\author.txt file (2nd line)
     * @param character
     * @return
     */
    private String getCurrentSkinName(String character)
    {
        String location = "C:\\Riot Games\\League of Legends\\game\\DATA\\Characters\\" + character + "\\" + "author.txt";
        String strLine ="Current skin failed to be found";
        int counter = 0;
        try {
            FileReader fr = new FileReader(location);
            BufferedReader in = new BufferedReader(fr);
            while ((strLine = in.readLine()) != null) {
                if (counter == 1) {
                    break;
                }
                counter++;
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strLine;
    }

    private void updateButtonMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_updateButtonMouseReleased
    }//GEN-LAST:event_updateButtonMouseReleased

    private void characterDropdownActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_characterDropdownActionPerformed
        String character = characterDropdown.getSelectedItem().toString();

        // Change name of Available Panel border
        availablePanelScroll.setBorder(BorderFactory.createTitledBorder("Available skins for " + character));

        // Get and display current skin picture
        String imageLocation = "C:\\Riot Games\\League of Legends\\game\\DATA\\Characters\\" + character + "\\" + character + ".jpg";
        String authorLocation = "C:\\Riot Games\\League of Legends\\game\\DATA\\Characters\\" + character + "\\author.txt";
        ImageIcon icon = new ImageIcon(imageLocation);
        icon = resizeImageIcon(icon);

        int count = 0;
        String strLine;
        currentSkinAuthor.setText("by: ");
        currentSkinName.setText("");
        try {
            BufferedReader in = new BufferedReader(new FileReader(authorLocation));
            count = 0;
            while ((strLine = in.readLine()) != null) {
                if (count == 0) {
                    // Print the author to the JLabel
                    currentSkinAuthor.setText("by: " + strLine);
                    count++;
                } else if (count == 1) {
                    // Print the skin name to the JLabel
                    currentSkinName.setText(strLine);
                    count++;
                }
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Get and display available skins
        getAvailableList(character);
    }//GEN-LAST:event_characterDropdownActionPerformed

    public SkinSelectPanel getActive()
    {
        return active;
    }
    
    public void activator(String act)
    {
        // Get all SkinSelectPanels on screen
        Component[] children = availablePanel.getComponents();
        for (int i =0; i < children.length; i++)
        {
            if(children[i] instanceof SkinSelectPanel)
            {
                // Deactivate all highlights
                if(!((SkinSelectPanel)children[i]).getSkinName().equals(act))
                {
                    ((SkinSelectPanel)children[i]).deactivate();
                }
                // Activate one
                else if(((SkinSelectPanel)children[i]).getSkinName().equals(act))
                {
                    // Remove old files from Character folder
                    String dirName = "C:\\Riot Games\\League of Legends\\game\\DATA\\Characters\\" + characterDropdown.getSelectedItem().toString();
                    File dir = new File(dirName);

                    // Get all files in directory
                    File[] files = dir.listFiles();
                    for (File file : files)
                    {
                        if(!file.isDirectory())
                        {
                            // Delete each file
                            if (!file.delete())
                            {
                                // Failed to delete file
                                System.out.println("Failed to delete "+file);
                            }
                        }
                    }

                    // Copy new skin files
                    active = (SkinSelectPanel)children[i];
                    currentSkinName.setText(((SkinSelectPanel)children[i]).getSkinName());
                    currentSkinAuthor.setText(((SkinSelectPanel)children[i]).getSkinAuthor());

                    // Get all files in directory
                    String skinDirName = dirName +"\\" +((SkinSelectPanel)children[i]).getSkinName();
                    System.out.println(skinDirName);
                    files = new File(skinDirName).listFiles();
                    for (File copyMe : files)
                    {
                        System.out.println("copyMe: "+copyMe.toString());
                        if(!copyMe.isDirectory())
                        {
                            // Copy each file
                            copyFile(copyMe.toString(), dirName);
                        }
                    }

                    if(((SkinSelectPanel)children[i]).getActive() == false)
                    {
                        ((SkinSelectPanel)children[i]).activate(false);
                    }
                }
            }
        }
    }

    public void copyFile(String inFile, String outFile)
    {
        String[] sections = inFile.split("\\\\");
        outFile += "\\" +sections[sections.length-1];
        System.out.println("Infile: " +inFile);
        System.out.println("Outfile: " +outFile);
        try
        {
            FileChannel ic = new FileInputStream(inFile).getChannel();
            FileChannel oc = new FileOutputStream(outFile).getChannel();
            ic.transferTo(0, ic.size(), oc);
            ic.close();
            oc.close();
        }
        catch(IOException ioe)
        {
            ioe.printStackTrace();
        }
    }

    public ImageIcon resizeImageIcon(ImageIcon givenImage)
    {
        int denominator = 3;
        Image img = givenImage.getImage();
        if(img.getWidth(null) < 676)
        {
            denominator = 1;
        }
        BufferedImage bi = new BufferedImage(img.getWidth(null)/denominator, img.getHeight(null)/denominator, BufferedImage.TYPE_INT_ARGB);
        bi.getGraphics().drawImage(img, 0, 0, img.getWidth(null)/denominator, img.getHeight(null)/denominator, null, null);
        return new ImageIcon(bi);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new SkinChooser().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel availablePanel;
    private javax.swing.JScrollPane availablePanelScroll;
    private javax.swing.JComboBox characterDropdown;
    private javax.swing.JLabel currentSkinAuthor;
    private javax.swing.JLabel currentSkinName;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JButton updateButton;
    // End of variables declaration//GEN-END:variables
}